package com.ljkj.cordial.chat.ui.views;

import android.text.TextUtils;

import com.lanjiu.lib.business.FileTransmissionManager;
import com.lanjiu.lib.business.OriginalPictureVideoTransmissionCreator;
import com.lanjiu.lib.business.TransmissionConstant;
import com.lanjiu.lib.business.listener.FileTransmissionListener;
import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.DelGroupMsgDto;
import com.lanjiu.lib.imclient.dto.DeleteMessageDto;
import com.lanjiu.lib.imclient.dto.FriendDto;
import com.lanjiu.lib.imclient.dto.GroupMemberDto;
import com.lanjiu.lib.imclient.dto.chat.ChatMessageDto;
import com.lanjiu.lib.imclient.dto.chat.FileDto;
import com.lanjiu.lib.imclient.dto.chat.PictureDto;
import com.lanjiu.lib.imclient.dto.chat.TextDto;
import com.lanjiu.lib.imclient.dto.chat.VideoDto;
import com.lanjiu.lib.imclient.dto.chat.VoiceDto;
import com.lanjiu.lib.imclient.dto.extra.ChatFriendMsgDto;
import com.lanjiu.lib.imclient.dto.extra.ChatGroupMsgDto;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.ui.ChatUtils;
import com.ljkj.cordial.chat.ui.IView;
import com.nic.view.util.JLog;
import com.yanzhenjie.album.AlbumFile;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/12/6 16:01
 */
public class GroupChatView extends IView {

    private GroupChatCallback mCallback;

    public GroupChatView(GroupChatCallback mCallback) {
        this.mCallback = mCallback;
    }

    public void doDeleteFriendChat(String msgIds, String friendUserId, String friendUserType, String msgFromIds, String timestamps, String chatTypes, String serverPaths) {
        DeleteMessageDto deleteMessageDto = new DeleteMessageDto();
        deleteMessageDto.setFriendUserId(friendUserId);
        deleteMessageDto.setFriendUserType(friendUserType);
        deleteMessageDto.setMessageIds(msgIds);
        deleteMessageDto.setMsgFromIds(msgFromIds);
        deleteMessageDto.setTimestamps(timestamps);
        deleteMessageDto.setChatTypes(chatTypes);
        deleteMessageDto.setServerPaths(serverPaths);

        int action = UserPreferences.isRegistered() ? EventConstants.Action.DEL_FRIEND_OFF_MESSAGE_REGIST : EventConstants.Action.DEL_FRIEND_OFF_MESSAGE_TOURIST;
        sendChatMessage(action, deleteMessageDto.toJson());
    }

    public void doDeleteGroupChat(String msgIds, String groupId, String msgFromIds, String timestamps, String chatTypes, String serverPaths) {
        DelGroupMsgDto delGroupMsgDto = new DelGroupMsgDto();
        delGroupMsgDto.setMsgIds(msgIds);
        delGroupMsgDto.setChatTypes(chatTypes);
        delGroupMsgDto.setServerPaths(serverPaths);
        delGroupMsgDto.setTimestamps(timestamps);
        delGroupMsgDto.setMemberIds(msgFromIds);
        delGroupMsgDto.setGroupId(groupId);

        sendChatMessage(EventConstants.Action.DEL_GROUP_OFF_MESSAGE, delGroupMsgDto.toJson());
    }

    public void doSendChatToFriend(FriendDto friendDto, ChatTableBean msg, AlbumFile file) {
        ChatFriendMsgDto chatFriendMsgDto = new ChatFriendMsgDto();
        chatFriendMsgDto.setFriendDto(friendDto);

        ChatMessageDto chatMessageDto = new ChatMessageDto();
        String msgId = TextUtils.isEmpty(msg.getMsgId()) ? ChatUtils.createMessageId(msg.getId(), UserPreferences.getUserId(), friendDto.getFriendUserId(), msg.getMsgTime()) : msg.getMsgId();
        chatMessageDto.setMsgId(msgId);
        msg.setMsgId(chatMessageDto.getMsgId());
        JLog.e(chatMessageDto.getMsgId());
        chatFriendMsgDto.setChatMessageDto(chatMessageFactory(chatMessageDto, msg, file, null));

        int action = UserPreferences.isRegistered() ? EventConstants.Action.FRIEND_CHAT_REGISTERED : EventConstants.Action.FRIEND_CHAT_TOURISTS;
        sendChatMessage(action, chatFriendMsgDto.toJson());
    }

    public void doSendFileChatToFriend(FriendDto friendDto, ChatTableBean msg, AlbumFile file, boolean isRetry) {
        ChatFriendMsgDto chatFriendMsgDto = new ChatFriendMsgDto();
        chatFriendMsgDto.setFriendDto(friendDto);

        ChatMessageDto chatMessageDto = new ChatMessageDto();
        String msgId = TextUtils.isEmpty(msg.getMsgId()) ? ChatUtils.createMessageId(msg.getId(), UserPreferences.getUserId(), friendDto.getFriendUserId(), msg.getMsgTime()) : msg.getMsgId();
        chatMessageDto.setMsgId(msgId);
        msg.setMsgId(chatMessageDto.getMsgId());
        boolean isPicture = msg.getChatType() == MsgType.Picture;
        FileTransmissionManager.getInstance().buildUploader()
                .targetPath(file.getPath())
                .friend(OriginalPictureVideoTransmissionCreator.friend(UserPreferences.isRegistered(), friendDto.getFriendUserId(), UserPreferences.getUserId(), isPicture))
                .onFileReceiver(new FileTransmissionListener.OnFileSenderListener() {
                    @Override
                    public void onStart() {
                        Logger.print("=============>onStart");
                    }

                    @Override
                    public void onProgress(int progress) {
                        Logger.print("=============>" + progress);
                    }

                    @Override
                    public void onComplete(String path) {
                        msg.setFileUrl(path);
                        DbController.getInstance().getWrite().getChatTableBeanDao().update(msg);
                        chatFriendMsgDto.setChatMessageDto(chatMessageFactory(chatMessageDto, msg, file, path));
                        int action = UserPreferences.isRegistered() ? EventConstants.Action.FRIEND_CHAT_REGISTERED : EventConstants.Action.FRIEND_CHAT_TOURISTS;
                        sendChatMessage(action, chatFriendMsgDto.toJson());
                    }

                    @Override
                    public void onError(int code, String str) {
                        Logger.print("=============>" + str);
                        if (code == TransmissionConstant.TRANSMISSION_TASK_REPET) {
                            String fileUrl = msg.getFileUrl();
                            if (TextUtils.isEmpty(fileUrl)) {
                                if (isRetry) {
                                    doSendFileChatToFriend(friendDto, msg, file, false);
                                } else {
                                    if (mCallback != null)
                                        mCallback.onSendChatCallback(IMSContacts.ResponseCode.FAILURE, "文件上传失败", chatMessageDto.getMsgId());
                                }
                            } else {
                                chatFriendMsgDto.setChatMessageDto(chatMessageFactory(chatMessageDto, msg, file, fileUrl));
                                int action = UserPreferences.isRegistered() ? EventConstants.Action.FRIEND_CHAT_REGISTERED : EventConstants.Action.FRIEND_CHAT_TOURISTS;
                                sendChatMessage(action, chatFriendMsgDto.toJson());
                            }
                        } else {
                            if (mCallback != null)
                                mCallback.onSendChatCallback(IMSContacts.ResponseCode.FAILURE, str, chatMessageDto.getMsgId());
                        }
                    }
                }).upload();
    }

    public void doSendChatToGroup(GroupMemberDto groupMemberDto, ChatTableBean msg, AlbumFile file, String atIds) {
        ChatGroupMsgDto chatGroupMsgDto = new ChatGroupMsgDto();
        chatGroupMsgDto.setGroupMemberDto(groupMemberDto);
        chatGroupMsgDto.setAt(atIds);

        ChatMessageDto chatMessageDto = new ChatMessageDto();
        String msgId = TextUtils.isEmpty(msg.getMsgId()) ? ChatUtils.createMessageId(msg.getId(), UserPreferences.getUserId(), groupMemberDto.getGroup().getGroupId(), msg.getMsgTime()) : msg.getMsgId();
        chatMessageDto.setMsgId(msgId);
        msg.setMsgId(chatMessageDto.getMsgId());
        chatGroupMsgDto.setChatMessageDto(chatMessageFactory(chatMessageDto, msg, file, null));

        int action = UserPreferences.isRegistered() ? EventConstants.Action.GROUP_CHAT_REGISTERED : EventConstants.Action.GROUP_CHAT_TOURISTS;
        sendChatMessage(action, chatGroupMsgDto.toJson());
    }

    public void doSendFileChatToGroup(GroupMemberDto groupMemberDto, ChatTableBean msg, AlbumFile file, boolean isRetry, String atIds) {
        ChatGroupMsgDto chatGroupMsgDto = new ChatGroupMsgDto();
        chatGroupMsgDto.setGroupMemberDto(groupMemberDto);
        chatGroupMsgDto.setAt(atIds);

        ChatMessageDto chatMessageDto = new ChatMessageDto();
        String msgId = TextUtils.isEmpty(msg.getMsgId()) ? ChatUtils.createMessageId(msg.getId(), UserPreferences.getUserId(), groupMemberDto.getGroup().getGroupId(), msg.getMsgTime()) : msg.getMsgId();
        chatMessageDto.setMsgId(msgId);
        msg.setMsgId(chatMessageDto.getMsgId());
        boolean isPicture = msg.getChatType() == MsgType.Picture;
        boolean isRegistered = UserPreferences.isRegistered(groupMemberDto.getGroup().getGroupType());
        FileTransmissionManager.getInstance().buildUploader()
                .targetPath(file.getPath())
                .group(OriginalPictureVideoTransmissionCreator.group(isRegistered, isRegistered, UserPreferences.isRegistered(), groupMemberDto.getGroup().getGroupId(), groupMemberDto.getGroupMemberId(), UserPreferences.getUserId(), isPicture))
                .onFileReceiver(new FileTransmissionListener.OnFileSenderListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onProgress(int progress) {
                    }

                    @Override
                    public void onComplete(String path) {
                        msg.setFileUrl(path);
                        DbController.getInstance().getWrite().getChatTableBeanDao().update(msg);
                        chatGroupMsgDto.setChatMessageDto(chatMessageFactory(chatMessageDto, msg, file, path));
                        int action = UserPreferences.isRegistered() ? EventConstants.Action.GROUP_CHAT_REGISTERED : EventConstants.Action.GROUP_CHAT_TOURISTS;
                        sendChatMessage(action, chatGroupMsgDto.toJson());
                    }

                    @Override
                    public void onError(int code, String str) {
                        Logger.print("=============>" + str);
                        if (code == TransmissionConstant.TRANSMISSION_TASK_REPET) {
                            String fileUrl = msg.getFileUrl();
                            if (TextUtils.isEmpty(fileUrl)) {
                                if (isRetry) {
                                    doSendFileChatToGroup(groupMemberDto, msg, file, false, atIds);
                                } else {
                                    if (mCallback != null)
                                        mCallback.onSendChatCallback(IMSContacts.ResponseCode.FAILURE, "文件上传失败", chatMessageDto.getMsgId());
                                }
                            } else {
                                chatGroupMsgDto.setChatMessageDto(chatMessageFactory(chatMessageDto, msg, file, fileUrl));
                                int action = UserPreferences.isRegistered() ? EventConstants.Action.GROUP_CHAT_REGISTERED : EventConstants.Action.GROUP_CHAT_TOURISTS;
                                sendChatMessage(action, chatGroupMsgDto.toJson());
                            }
                        } else {
                            if (mCallback != null)
                                mCallback.onSendChatCallback(IMSContacts.ResponseCode.FAILURE, str, chatMessageDto.getMsgId());
                        }
                    }
                }).upload();
    }

    @Override
    protected void onMessageEventHandle(MessageEvent event) {
        if (event.action() == EventConstants.Action.FRIEND_CHAT_TOURISTS ||
                event.action() == EventConstants.Action.FRIEND_CHAT_REGISTERED) {
            Logger.print("GroupChatView", event.toString());
            if (mCallback != null)
                mCallback.onSendChatCallback(event.code(), event.msg(), event.data());
        } else if (event.action() == EventConstants.Action.GROUP_CHAT_TOURISTS ||
                event.action() == EventConstants.Action.GROUP_CHAT_REGISTERED) {
            Logger.print("GroupChatView", event.toString());
            if (mCallback != null)
                mCallback.onSendChatCallback(event.code(), event.msg(), event.data());
        }
    }

    public interface GroupChatCallback {
        void onSendChatCallback(int code, String msg, String msgId);
    }

    private ChatMessageDto chatMessageFactory(ChatMessageDto chatMessageDto, ChatTableBean msg, AlbumFile file, String serverPath) {
        if (msg.getChatType() == MsgType.Text) {
            TextDto textDto = new TextDto();
            textDto.setContent(msg.getTextMsg());
            textDto.setLength(String.valueOf(msg.getTextMsg().length()));
            chatMessageDto.setText(textDto);
            chatMessageDto.setChatType(IMSContacts.MsgContentType.TEXT);
        } else if (msg.getChatType() == MsgType.Voice) {
            VoiceDto voiceDto = new VoiceDto();
            voiceDto.setContent(file.getPath());
            voiceDto.setLength(file.getSize());
            chatMessageDto.setVoice(voiceDto);
            chatMessageDto.setChatType(IMSContacts.MsgContentType.VOICE);
        } else if (msg.getChatType() == MsgType.Picture) {
            PictureDto pictureDto = new PictureDto();
            pictureDto.setThumbnail(file.getThumbPath());
            pictureDto.setUrl(serverPath);
            pictureDto.setLength(file.getSize());
            chatMessageDto.setPicture(pictureDto);
            chatMessageDto.setChatType(IMSContacts.MsgContentType.PICTURE);
        } else if (msg.getChatType() == MsgType.Video) {
            VideoDto videoDto = new VideoDto();
            videoDto.setThumbnail(file.getThumbPath());
            videoDto.setUrl(serverPath);
            videoDto.setLength(file.getSize());
            chatMessageDto.setVideo(videoDto);
            chatMessageDto.setChatType(IMSContacts.MsgContentType.VIDEO);
        } else if (msg.getChatType() == MsgType.ANNEX) {
            FileDto fileDto = new FileDto();
            fileDto.setUrl(serverPath);
            fileDto.setLength(file.getSize());
            chatMessageDto.setFile(fileDto);
            chatMessageDto.setChatType(IMSContacts.MsgContentType.FILE);
        }
        return chatMessageDto;
    }
}
